﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PromoOffersCrawler.Crawler.Data
{
    public class Repository
    {
        private object threadSafeInsertUpdate = new object();

        private int queryFlushLimit = 10000;

        private Entities db = new Entities();

        public void Insert(List<Offer> offers)
        {
            lock (threadSafeInsertUpdate)
            {
                int flushCounter = 0;
                foreach (var item in offers)
                {
                    db.Offers.Add(item);
                    flushCounter++;

                    flushCounter = SaveWithFlushLimit(flushCounter);
                }

                db.SaveChanges();
            }
        }

        private int SaveWithFlushLimit(int flushCounter)
        {
            if (flushCounter > queryFlushLimit)
            {
                db.SaveChanges();
                flushCounter = 0;
            }
            return flushCounter;
        }


        public int GetTypeId(string name, int retryCounter = 3)
        {
            lock (db)
            {
                var dbEntry = db.OfferTypes.FirstOrDefault(x => x.Name == name);

                if (dbEntry == null)
                {
                    try
                    {
                        dbEntry = new OfferType() { Name = name };
                        db.OfferTypes.Add(dbEntry);
                        db.SaveChanges();

                    }
                    catch (Exception e)
                    {
                        if (retryCounter == 0)
                            throw;

                        return GetTypeId(name, retryCounter--);
                    }
                }

                return dbEntry.ID;
            }

        }
    }
}
